package com.bz.security;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bz.common.RedisServiceUtil;
import com.bz.common.UserConfig;
import com.bz.dao.RoleDao;
import com.bz.dao.UserDao;
import com.bz.entity.UserEntity;

@Service
@EnableWebSecurity
public class AuthUserService implements UserDetailsService {

    @Autowired
    private UserDao          userDao;

    @Autowired
    private RoleDao          roleDao;

    @Autowired
    private RedisServiceUtil redisServiceUtil;

    public UserDetails loadUserByToken(String username) throws UsernameNotFoundException {

        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("username is null");
        }

        // 从redis获取用户登录信息
        String ustr = redisServiceUtil.get(UserConfig.getUserKey(username));
        if (StringUtils.isNotEmpty(ustr)) {
            UserEntity user = JSON.parseObject(ustr, UserEntity.class);
            AuthUserDto au = new AuthUserDto(user, null);
            if (null != user && null != user.getRoleMap() && user.getRoleMap().size() > 0) {
                au.setRoleMap(user.getRoleMap());
            }
            return au;

        }
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("username is null");
        }
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEntity::getUsername, username).eq(UserEntity::getStatus, "1");

        UserEntity userEntity = userDao.selectOne(queryWrapper);
        if (null == userEntity) {
            throw new UsernameNotFoundException("username is not found");
        }

        UserEntity userDto = JSON.parseObject(JSON.toJSONString(userEntity), UserEntity.class);

        List<GrantedAuthority> authorities = new ArrayList<>();
        userDto.setUrls(roleDao.getUrls(userDto.getId()));
        Map<String, Object> parMap = new HashMap<>();
        parMap.put("userId", userDto.getId());
        userDto.setRoleList(roleDao.getUserRole(parMap));
        AuthUserDto authUserDto = new AuthUserDto(userDto, authorities);
        return authUserDto;
    }

}
